package leetcode;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2022-01-23 17:58
 **/
public class LeetCode2034 {

    Map<Integer, Integer> map;
    TreeMap<Integer, Integer> prices;
    int curTime;

    public LeetCode2034() {
        map = new HashMap<>();
        prices = new TreeMap<>();
        curTime = 1;
    }

    public void update(int timestamp, int price) {
        curTime = Math.max(curTime, timestamp);
        //获取某个时间戳之前的价格,无就为0
        int prevPrice = map.getOrDefault(timestamp, 0);
        //覆盖原来的 时间戳:价格
        map.put(timestamp, price);
        //如果prevPrice>0,需要更新在prices中的原来的key为prevPrice对应的数据
        if (prevPrice > 0) {
            prices.put(prevPrice, prices.get(prevPrice) - 1);
            //如果prices对应的的value为0说明之前只有一个时间戳对应的value为prevPrice,而现在已经更新了value,那么现在就可以移除prices中key为prevPrice的数据

            if (prices.get(prevPrice) == 0) {
                prices.remove(prevPrice);
            }
        }
        //将当前price加入到prices,对应的value初值为1
        prices.put(price, prices.getOrDefault(price, 0) + 1);
    }

    public int current() {
        return map.get(curTime);
    }

    public int maximum() {
        return prices.lastKey();
    }

    public int minimum() {
        return prices.firstKey();
    }

}
